package cn.wzc.crystal.platform.enhance;

import cn.wzc.crystal.platform.enhance.support.LogEnhancer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.aop.Advisor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Slf4j
//@Component
@RequiredArgsConstructor
public class EnhanceConfigure {

	private final EnhanceProperties enhanceProperties;

	private final ApplicationContext context;

	@Bean
	public Advisor defaultPointcutAdvisor() {
		// just log
		log.info("enhance packages: {}", Arrays.toString(enhanceProperties.getAdvicePackage()));

		// 找到目标类做切面
		LogEnhancer logTraceAdvice = context.getBean(LogEnhancer.class);
		JdkRegexpMethodPointcut pointcut = new JdkRegexpMethodPointcut();
		pointcut.setPatterns(".*");
		pointcut.setClassFilter(clazz -> {
			// 只增加service类
			if (null == clazz.getAnnotation(Service.class)) {
				return false;
			}
			for (String packageName : ArrayUtils.nullToEmpty(enhanceProperties.getAdvicePackage())) {
				if (null == clazz.getPackage()) {
					return false;
				}
				if (clazz.getPackage().getName().startsWith(packageName)) {
					return true;
				}
			}
			return false;
		});

		// 配置增强类advisor
		DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
		advisor.setPointcut(pointcut);
		advisor.setAdvice(logTraceAdvice);
		return advisor;
	}

}